import axios from 'axios';
import { DeepSeekHash } from './challenge.js'; 
import APIException from "./exceptions/APIException.js";
import EX from "./exceptions/Exception.js";
import { generateCookie } from './cookie.js'
import _ from "lodash";


// 伪装headers
const FAKE_HEADERS = {
  Accept: "*/*",
  "Accept-Encoding": "gzip, deflate, br, zstd",
  "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7",
  Origin: "https://chat.deepseek.com",
  Pragma: "no-cache",
  Priority: "u=1, i",
  Referer: "https://chat.deepseek.com/",
  "Sec-Ch-Ua":
    '"Chromium";v="130", "Google Chrome";v="130", "Not?A_Brand";v="99"',
  "Sec-Ch-Ua-Mobile": "?0",
  "Sec-Ch-Ua-Platform": '"Windows"',
  "Sec-Fetch-Dest": "empty",
  "Sec-Fetch-Mode": "cors",
  "Sec-Fetch-Site": "same-origin",
  "User-Agent":
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36",
  "X-App-Version": "20241129.1"
};
// 插冷鸡WASM文件路径
const WASM_PATH = './sha3_wasm_bg.7b9ca65ddd.wasm';

let deepSeekHashInstance = null;

export const Challenge = async (refreshToken) => {
    try {
        const challengeResponse = await getChallengeResponse(refreshToken, '/api/v0/chat/completion');
        const challenge = await answerChallenge(challengeResponse, '/api/v0/chat/completion');
        return { code: 0, challenge };
    } catch (error) {
        console.error('Challenge execution failed:', error);
        throw error;
    }
}

/**
 * 碰撞challenge答案
 * 
 */
async function answerChallenge(response, targetPath) {
    const { algorithm, challenge, salt, difficulty, expire_at, signature } = response;
    const deepSeekHash = new DeepSeekHash();
    await deepSeekHash.init(WASM_PATH);
    const answer = deepSeekHash.calculateHash(algorithm, challenge, salt, difficulty, expire_at);
    return Buffer.from(JSON.stringify({
      code: 1,
      algorithm,
      challenge,
      salt,
      answer,
      signature,
      target_path: targetPath
    })).toString('base64');
  }
  
  /**
   * 获取challenge响应
   *
   * @param refreshToken token
   */
  async function getChallengeResponse(refreshToken, targetPath) {
    const result = await axios.post('https://chat.deepseek.com/api/v0/chat/create_pow_challenge', {
      target_path: targetPath
    }, {
      headers: {
        Authorization: `Bearer ${refreshToken}`,
        ...FAKE_HEADERS,
        Cookie: await generateCookie()
      },
      timeout: 15000,
      validateStatus: () => true,
    });
    const { biz_data: { challenge } } = checkResult(result, refreshToken);
    return challenge;
  }

/**
 * 检查请求结果
 *
 * @param result 结果
 * @param refreshToken 用于刷新access_token的refresh_token
 */
function checkResult(result, refreshToken) {
    if (!result.data) return null;
    const { code, data, msg } = result.data;
    if (!_.isFinite(code)) return result.data;
    if (code === 0) return data;
    if (code == 40003) return
}